<template>
  <div class="approval">
    <el-card class="box-card" style="margin-top: 110px;overflow:scroll;">
      <div class="head-title2">
        <div class='title'>
          {{$t('achievements.title1')}}
        </div>
        <div class="info">
          <el-tooltip placement="left">
            <div slot="content">
              {{define}}
            </div>
            <div class="btns"></div>
          </el-tooltip>
        </div>
      </div>
      <div class="menu-search">
        <!-- 时间 -->
        <div class="menu-title">
          <div class="searchItem searchItem-date">
            <span>{{$t('approvalDetail.riskTime')}}</span>
            <el-date-picker
              size="small"
              v-model="listQuery.startDate"
              type="date"
              value-format="yyyy-MM-dd"
              :placeholder="$t('rule.beginDate')"
              :picker-options="startDatePicker"
            ></el-date-picker>
            <b>{{$t('approval.go')}}</b>
            <el-date-picker
              size="small"
              v-model="listQuery.endDate"
              type="date"
              value-format="yyyy-MM-dd"
              :placeholder="$t('rule.endDate')"
              :picker-options="endDatePicker"
            ></el-date-picker>
          </div>
          <!-- APP渠道 -->
          <div class="searchItem">
            <span>{{$t('ElectricChannel.AppChannel')}}</span>
            <el-select v-model="listQuery.channel" size="small">
              <el-option
                v-for="item in appChannel"
                :key="item.channel"
                :label="item.org_name"
                :value="item.channel"
              ></el-option>
            </el-select>
          </div>
        </div>
        <div class="menu-title-btn">
          <button type="button" @click="search">{{$t('btn.query')}}</button>
          <button type="button" @click="reset">{{$t('btn.reset')}}</button>
          <!-- 补偿导入 -->
          <button type='button' @click="importFn" v-if="realTimeDate_btn_import">
            {{$t('realTimeData.compensateImport')}}
          </button>
        </div>
      </div>
    </el-card>
    <el-card class="box-card" style="margin-top: 10px;margin-bottom: 20px;">
      <div class="title">{{$t('DailyStatistics.ListDetails')}}</div>
      <el-table
        :sum-text="$t('ApprReport.total')"
        v-loading="listLoading"
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%; margin-top: 5px;"
        @selection-change="handleSelectionChange"
        border
        size="mini"
      >
        <!-- 日期 -->
        <el-table-column
          header-align="center"
          align="center"
          prop="date"
          width="140"
          :label="$t('overdueData.time')"
        ></el-table-column>
        <!-- 渠道 -->
        <el-table-column
          header-align="center"
          align="center"
          width="140"
          :label="$t('productManage.channels')"
        >
        <template>
          <span>{{currentChannel}}</span>
        </template>
        </el-table-column>
        <!-- 安装量 -->
        <el-table-column
          header-align="center"
          align="center"
          prop="installNo"
          width="140"
          :label="$t('ElectricChannel.installs')"
        ></el-table-column>
        <!-- 注册量 -->
        <el-table-column
          header-align="center"
          align="center"
          prop="registerNo"
          width="140"
          :label="$t('ElectricChannel.registrations')"
        ></el-table-column>
        <!-- 注册率 -->
        <el-table-column
          header-align="center"
          align="center"
          prop="registerRate"
          width="140"
          :label="$t('realTimeData.RegistRate')"
        ></el-table-column>
        <!-- 申请量 -->
        <el-table-column
          header-align="center"
          align="center"
          prop="applyNo"
          width="140"
          :label="$t('ElectricChannel.applyNum')"
        ></el-table-column>
        <!-- 申请率 -->
        <el-table-column
          header-align="center"
          align="center"
          prop="applyRate"
          width="140"
          :label="$t('realTimeData.ApplyRate')"
        ></el-table-column>
        <!-- 机审通过率 -->
        <el-table-column
          header-align="center"
          align="center"
          prop="machinePassingRate"
          width="140"
          :label="$t('realTimeData.AirAppRate')"
        ></el-table-column>
        <!-- 放款量 -->
        <el-table-column
          header-align="center"
          align="center"
          prop="loanNo"
          width="140"
          :label="$t('ElectricChannel.loanNum')"
        ></el-table-column>
        <!-- 人审通过率 -->
        <el-table-column
          header-align="center"
          align="center"
          prop="humanPassingRate"
          width="140"
          :label="$t('realTimeData.TrialPassRate')"
        ></el-table-column>
        <!-- 当日首逾率 -->
        <el-table-column
          header-align="center"
          align="center"
          prop="firstPassRate"
          width="140"
          :label="$t('dashboard.currentDayRate')"
        ></el-table-column>
        <!-- S1催回率 -->
        <el-table-column
          header-align="center"
          align="center"
          prop="oneRushRate"
          width="140"
          :label="$t('dashboard.s1Rate')"
        ></el-table-column>
        <!-- 七日续贷率 -->
        <el-table-column
          header-align="center"
          align="center"
          prop="sevenRenewalRate"
          width="140"
          :label="$t('dashboard.weekdayRate')"
        ></el-table-column>
        <!-- 综合逾期率 -->
        <el-table-column
          header-align="center"
          align="center"
          prop="historicalOverdueRate"
          width="140"
          :label="$t('overdueData.firstOverAll')"
        ></el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="listQuery.page"
          :page-sizes="[5, 10, 20, 30]"
          :page-size="listQuery.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
    </el-card>
    <!-- 补偿导入 -->
    <el-dialog
      :title="$t('realTimeData.compensateImport')"
      :visible.sync="importDialogVisible"
      style="text-align: center;"
      center
      width="40%">
      <el-form :model="form" :rules="rules" ref="form" label-width="110px">
        <!-- 选择时间 -->
        <el-form-item :label="$t('ApprReport.choiceTime')" required>
          <el-col :span="11">
            <el-form-item prop="startDate">
              <el-date-picker size="small" type="date" :placeholder="$t('rule.beginDate')" v-model="form.startDate" style="width: 100%;" value-format="yyyy-MM-dd"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col class="line" :span="2">-</el-col>
          <el-col :span="11">
            <el-form-item prop="endDate">
              <el-date-picker size="small" type="date" :placeholder="$t('rule.endDate')" v-model="form.endDate" style="width: 100%;" value-format="yyyy-MM-dd"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-form-item>
        <!-- 选择渠道 -->
        <el-form-item :label="$t('realTimeData.chooseChannel')" prop="channel">
          <el-select v-model="form.channel" size="small">
            <el-option
              v-for="item in appChannel"
              :key="item.channel"
              :label="item.org_name"
              :value="item.channel"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 文件类型 -->
        <el-form-item :label="$t('realTimeData.fileType')" prop="compensateType">
          <el-select v-model="form.compensateType" size="small">
            <el-option
              v-for="(item, index) in fileTypeArr"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 上传文件 -->
        <el-form-item :label="$t('realTimeData.uploadFile')" ref='file' prop="file">
          <el-checkbox-group v-model="form.file">
          </el-checkbox-group>
          <el-button 
          v-loading.fullscreen.lock="fullscreenLoading"
          :element-loading-text="$t('realTimeData.loading')" 
          element-loading-spinner="el-icon-loading" 
          element-loading-background="rgba(0, 0, 0, 0.8)"
          type="primary" 
          @click.stop="uploadFiles">{{$t('AppUpgrade.subUpload')}}</el-button>
          <form action="" id="videoForm">
            <input ref="referenceUpload" type="file" value="点击上传文件" @change='onUpload' name="file" class="hiddenInput">
          </form>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="importDialog('form')" :disabled="importDis">{{$t('btn.complete')}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { toPercent } from 'utils/index';
import { getChannels } from "api/customQuery/index";
import { operational, compensateInstall } from 'api/synManager/realTimeData/index'
export default {
  data() {
    return {
      define: '',
      fullscreenLoading: false,
      fileTypeArr: [
        {
          value: 1,
          label: this.$t('realTimeData.InstallData')
        },
        {
          value: 2,
          label: this.$t('realTimeData.RegistData')
        },
      ],
      importDis: false,
      form: {
        startDate: '', // 开始时间
        endDate: '', // 结束时间
        channel: '', // 渠道
        compensateType: '', // 文件类型
        file: ''
      },
      rules: {
        startDate: [
          { required: true, message: this.$t('rule.ruleStartTime') }
        ],
        endDate: [
          { required: true, message: this.$t('rule.ruleEndTime') }
        ],
        channel: [
          { required: true, message: this.$t('userGroupManager.ruleChannel'), trigger: 'change' }
        ],
        compensateType: [
          { required: true, message: this.$t('realTimeData.ruleFileType'), trigger: 'change' }
        ],
        file: [
          { required: true, message: this.$t('realTimeData.ruleUploadFiles'), trigger: 'change' }
        ]
      },
      importDialogVisible: false,
      realTimeDate_btn_import: false,
      startDatePicker: this.disStartDate(),
      endDatePicker: this.disEndDate(),
      listLoading: false,
      total: null,
      listQuery: {
        limit: 5,
        page: 1,
        startDate: '',
        endDate: '',
        channel: ''
      },
      appChannel: [],
      tableData: [],
      multipleSelection: [],
      currentChannel: ''
    };
  },
  computed: {
    ...mapGetters(["elements", "realTimeDataPage", 'getReportDefine'])
  },
  created() {
    if (this.realTimeDataPage.has(this.$route.path)) {
      this.listQuery = this.realTimeDataPage.get(this.$route.path)
    }
    this.getTime();
    // 渠道下拉
    getChannels().then(res => {
      this.appChannel = res.data;
      this.listQuery.channel = this.appChannel[0].channel;
      this.currentChannel = this.appChannel[0].org_name;
      this.getList();
    });
    this.realTimeDate_btn_import = this.elements['realTimeDate:btn_import'];
    // 获取报表定义
    this.getReportDefine.forEach(item => {
      if (item.dictCode === 'OPERATIONAL_REAL-TIME_REPORT') {
        this.define = item.dictValue
      }
    })
  },
  methods: {
    // 点击上传文件
    uploadFiles() {
      this.$el.querySelector('.hiddenInput').click()
    },
    // 上传成功后的回调
    onUpload(e){
      let $target = e.target || e.srcElement;
      let filename = $target.value;
      let suffix = filename.substring(filename.lastIndexOf('.') + 1);
      if (suffix !== 'csv') {
        this.$message({
          showClose: true,
          type: "warning",
          message: this.$t('realTimeData.fileFormat')
        });
        document.getElementById('videoForm') && document.getElementById('videoForm').reset()
      } else {
        let files = $target.files[0];
        if ( files === undefined || files === null || files === '') {
          return;
        }
        this.form.file = files;
        this.$refs.referenceUpload.value = null
      }
    },
    // 点击补偿导入
    importFn() {
      this.$nextTick(()=>{
        if (this.$refs.form !== undefined) {
          this.$refs.form.resetFields() // 等弹窗里的form表单的dom渲染完在执行this.$refs.form.resetFields()，去除验证
        }
      });
      this.importDialogVisible = true
    },
    // 补偿导入确认
    importDialog(formName) {
      const set = this.$refs;
      set[formName].validate(valid => {
        if (valid) {
          this.$confirm(this.$t('approvalDetail.cue1'), {
            confirmButtonText: this.$t('btn.confirm'),
            cancelButtonText: this.$t('btn.cancel'),
            type: "warning",
            center: true
          })
          .then(() => {
            this.importDis = true // 禁用完成按钮
            this.fullscreenLoading = true // 加载中
            let obj = new FormData()
            obj.append('file', this.form.file)
            obj.append('startDate', this.form.startDate)
            obj.append('endDate', this.form.endDate)
            obj.append('channel', this.form.channel)
            obj.append('compensateType', this.form.compensateType)
            compensateInstall(obj)
            .then(res => {
              this.importDis = false
              if (res.status === 200) {
                this.fullscreenLoading = false;
                this.importDialogVisible = false
                this.getList();
                this.$message({
                  showClose: true,
                  message: this.$t('realTimeData.importSus'),
                  type: 'success'
                });
              } else {
                this.$message({
                  showClose: true,
                  type: "warning",
                  message: res.message
                })
                this.fullscreenLoading = false;
              }
            })
          })
          .catch(() => {
            this.$message({
              showClose: true,
              type: "info",
              message: this.$t('orderQuery.cue2')
            });
          });
        } else {
          return false;
        }
      });
    },
    disStartDate(){
      return {
        disabledDate(time){
          return time.getTime() > Date.now(); // 禁用当天及以上
        }
      }
    },
    disEndDate(){
      return {
        disabledDate(time){
          return time.getTime() > Date.now(); // 禁用当天及以上
        }
      }
    },
    getTime() {
      this.listQuery.startDate = this.GetDateStr(-6);
      this.listQuery.endDate = this.GetDateStr(0);
    },
    GetDateStr(AddDayCount) {
      let dd = new Date();
      dd.setDate(dd.getDate() + AddDayCount);// 获取AddDayCount天后的日期
      let y = dd.getFullYear();
      let m = (dd.getMonth() + 1) < 10 ? '0' + (dd.getMonth() + 1) : (dd.getMonth() + 1); // 获取当前月份的日期，不足10补0
      let d = dd.getDate() < 10 ? '0' + dd.getDate() : dd.getDate(); // 获取当前几号，不足10补0
      return y + '-' + m + '-' + d;
    },
    getList() {
      if (this.listQuery.startDate === '' || this.listQuery.startDate === null || this.listQuery.startDate === undefined) {
        this.$message({
          showClose: true,
          type: "warning",
          message: this.$t('rule.ruleStartTime')
        });
      } else if (this.listQuery.endDate === '' || this.listQuery.endDate === null || this.listQuery.endDate === undefined) {
        this.$message({
          showClose: true,
          type: "warning",
          message: this.$t('rule.ruleEndTime')
        });
      } else {
        this.listLoading = true;
        this.$store.dispatch('saveRealTimeDataPage', { path: this.$route.path, listQuery: this.listQuery });
        operational(this.listQuery)
          .then(res => {
            if (res.status === 200) {
              this.listLoading = false;
              this.appChannel.forEach(item => {
                if (this.listQuery.channel === item.channel) {
                  this.currentChannel = item.org_name;
                }
              })
              res.data.queryOperationalList.forEach(item => {
                if (item.registerRate || item.applyRate || item.machinePassingRate ||item.humanPassingRate ||item.firstPassRate ||item.oneRushRate ||item.sevenRenewalRate ||item.historicalOverdueRate) {
                  item.registerRate = toPercent(item.registerRate);
                  item.applyRate = toPercent(item.applyRate);
                  item.machinePassingRate = toPercent(item.machinePassingRate);
                  item.humanPassingRate = toPercent(item.humanPassingRate);
                  item.firstPassRate = toPercent(item.firstPassRate);
                  item.oneRushRate = toPercent(item.oneRushRate);
                  item.sevenRenewalRate = toPercent(item.sevenRenewalRate);
                  item.historicalOverdueRate = toPercent(item.historicalOverdueRate);
                }
              })
              this.tableData = res.data.queryOperationalList;
              this.total = Number(res.data.total);
            } else {
              this.$message({
                showClose: true,
                type: "warning",
                message: res.message
              });
            }
          })
      }
    },
    //查询
    search() {
      this.listQuery.page = 1;
      this.getList();
    },
    //重置
    reset() {
      this.listQuery.limit = 5;
      this.listQuery.page = 1;
      this.listQuery.startDate = this.GetDateStr(-6);
      this.listQuery.endDate = this.GetDateStr(0);
      this.listQuery.channel = this.appChannel[0].channel;
    },
    //选中的数据
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList()
    }
  }
};
</script>

<style scoped lang='scss'>
.box-card {
  width: 95%;
  margin-left: 2.5%;
  margin-right: 2.5%;
}
.title {
  line-height: 30px;
  font-size: 16px;
  display: flex;
  align-items: center;
  font-weight: bold;
}
.title:before {
  display: block;
  content: "";
  width: 3px;
  height: 16px;
  background-color: #309afe;
}
.title:before {
  margin-right: 8px;
}
::before {
  box-sizing: inherit;
  -webkit-tap-highlight-color: transparent;
}
.menu-title {
  width: 100%;
  box-sizing: border-box;
  background: #ffffff;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  .searchItem {
    display: flex;
    align-items: center;
    padding: 10px 0;
    span {
      display: inline-block;
      width: 100px;
      text-align: right;
      font-size: 12px;
      color: #5f5f61;
      padding-right: 5px;
    }
    div:nth-child(2) {
      width: 150px;
    }
  }
  .searchItem-date {
    display: flex;
    align-items: center;
    padding: 10px 0;
    b {
      margin: 0 10px;
      font-weight: normal;
      font-size: 12px;
      color: #5f5f61;
    }
    div {
      width: 150px;
    }
  }
}
.menu-title-btn {
  padding: 10px 0;
  box-sizing: border-box;
  button {
    padding: 0 20px;
    height: 28px;
    background: #20a0ff;
    color: #fff;
    outline: none;
    border-width: 0;
    border-radius: 4px;
    font-size: 12px;
    margin-left: 10px;
    &:nth-child(1) {
      margin-left: 0;
    }
    &:nth-child(2) {
      background: #ebf5ff;
      color: #20a0ff;
      border: 1px solid #abd5ff;
    }
  }
  button[disabled] {
    padding: 0 20px;
    height: 28px;
    background: #c1e0ff;
    color: #fafbff;
    outline: none;
    border-width: 0;
    border-radius: 4px;
    font-size: 12px;
  }
}
.menu-list {
  padding: 20px 0;
  box-sizing: border-box;
  button {
    padding: 0 20px;
    height: 28px;
    background: #20a0ff;
    color: #fff;
    outline: none;
    border-width: 0;
    border-radius: 4px;
    font-size: 12px;
    margin-left: 10px;
    &:nth-child(1) {
      margin-left: 0;
    }
  }
  button[disabled] {
    padding: 0 20px;
    height: 28px;
    background: #c1e0ff;
    color: #fafbff;
    outline: none;
    border-width: 0;
    border-radius: 4px;
    font-size: 12px;
  }
}
.line {
  text-align: center;
}
.hiddenInput{
  display: none;
}
.head-title2 {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.btns {
  display: inline-block;
  width: 24px;
  height: 24px;
  background-size: cover;
  background-image: url("../../../assets/images/question-mark.svg");
}
</style>